'use client';

import { useRouter, useParams } from 'next/navigation';
import { useEffect, useState } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { Button } from '@/components/ui/button';
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { toast } from '@/components/ui/use-toast';
import { ArrowLeft } from 'lucide-react';
import Link from 'next/link';
import { getApiUrl } from '@/lib/utils';

const formSchema = z.object({
  siteId: z.string().min(1, '请选择工地'),
  type: z.enum(['material', 'labor', 'equipment', 'other'], {
    required_error: '请选择支出类型',
  }),
  amount: z.string().refine((val) => !isNaN(Number(val)) && Number(val) > 0, {
    message: '支出金额必须大于0',
  }),
  paymentDate: z.string().refine((val) => !isNaN(Date.parse(val)), {
    message: '请选择有效的支付日期',
  }),
  vendor: z.string().optional(),
  description: z.string().optional(),
});

type Site = {
  id: string;
  name: string;
  status: 'active' | 'completed' | 'paused';
};

const expenseTypeMap = {
  material: '材料费',
  labor: '人工费',
  equipment: '设备费',
  other: '其他费用',
} as const;

export default function EditExpensePage() {
  const router = useRouter();
  const params = useParams();
  const id = params.id as string;
  const [sites, setSites] = useState<Site[]>([]);
  const [isLoading, setIsLoading] = useState(true);

  const form = useForm<z.infer<typeof formSchema>>({
    resolver: zodResolver(formSchema),
  });

  useEffect(() => {
    async function loadData() {
      try {
        // 加载工地列表
        const sitesResponse = await fetch(getApiUrl('sites'));
        if (!sitesResponse.ok) throw new Error('加载工地列表失败');
        const sitesData = await sitesResponse.json();
        setSites(sitesData);

        // 加载支出详情
        const expenseResponse = await fetch(getApiUrl(`expenses/${id}`));
        if (!expenseResponse.ok) throw new Error('加载支出详情失败');
        const expense = await expenseResponse.json();

        // 设置表单默认值
        form.reset({
          siteId: expense.siteId,
          type: expense.type,
          amount: String(expense.amount),
          paymentDate: new Date(expense.paymentDate).toISOString().split('T')[0],
          vendor: expense.vendor || '',
          description: expense.description || '',
        });
      } catch {
        toast({
          variant: 'destructive',
          title: '加载失败',
          description: '无法加载数据，请刷新页面重试',
        });
      } finally {
        setIsLoading(false);
      }
    }
    loadData();
  }, [id, form]);

  async function onSubmit(values: z.infer<typeof formSchema>) {
    try {
      const response = await fetch(getApiUrl(`expenses/${id}`), {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          ...values,
          amount: Number(values.amount),
        }),
      });

      if (!response.ok) {
        throw new Error('提交失败');
      }

      toast({
        title: '更新成功',
        description: '支出记录已更新',
      });

      router.push(`/expenses/${id}`);
      router.refresh();
    } catch {
      toast({
        variant: 'destructive',
        title: '更新失败',
        description: '请稍后重试',
      });
    }
  }

  if (isLoading) {
    return <div>加载中...</div>;
  }

  return (
    <main className="container mx-auto p-4 space-y-4">
      <Button variant="ghost" asChild className="mb-4">
        <Link href={`/expenses/${id}`}>
          <ArrowLeft className="mr-2 h-4 w-4" />
          返回支出详情
        </Link>
      </Button>

      <h1 className="text-3xl font-bold tracking-tight">编辑支出</h1>

      <div className="max-w-xl">
        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">
            <FormField
              control={form.control}
              name="siteId"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>选择工地</FormLabel>
                  <Select
                    value={field.value}
                    onValueChange={field.onChange}
                  >
                    <FormControl>
                      <SelectTrigger>
                        <SelectValue placeholder="请选择工地" />
                      </SelectTrigger>
                    </FormControl>
                    <SelectContent>
                      {sites.map((site) => (
                        <SelectItem key={site.id} value={site.id}>
                          {site.name}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="type"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>支出类型</FormLabel>
                  <Select
                    value={field.value}
                    onValueChange={field.onChange}
                  >
                    <FormControl>
                      <SelectTrigger>
                        <SelectValue placeholder="请选择支出类型" />
                      </SelectTrigger>
                    </FormControl>
                    <SelectContent>
                      {Object.entries(expenseTypeMap).map(([value, label]) => (
                        <SelectItem key={value} value={value}>
                          {label}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="amount"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>支出金额</FormLabel>
                  <FormControl>
                    <Input
                      type="number"
                      step="0.01"
                      placeholder="请输入支出金额"
                      {...field}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="paymentDate"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>支付日期</FormLabel>
                  <FormControl>
                    <Input type="date" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="vendor"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>供应商</FormLabel>
                  <FormControl>
                    <Input placeholder="请输入供应商名称（选填）" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="description"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>备注说明</FormLabel>
                  <FormControl>
                    <Input placeholder="请输入备注说明（选填）" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <Button type="submit">保存修改</Button>
          </form>
        </Form>
      </div>
    </main>
  );
}